package com.blockchain.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtTokenUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    //生成令牌
    public String generateToken(int user_id){
        Date now=new Date();
        Date expiryDate=new Date(now.getTime()+expiration);

        return Jwts.builder()
                .claim("user_id",user_id)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }
    //验证令牌是否有效
    public boolean validateToken(String token){
        try {
            //密钥解析令牌，若无异常则有效
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

}
